package edu.xmut.yuepai.common.interceptor;

import cn.hutool.core.util.StrUtil;
import edu.xmut.yuepai.common.constant.AuthConstants;
import edu.xmut.yuepai.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;


@ConditionalOnClass(DispatcherServlet.class)
@Slf4j
@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        log.info("被访问，{}", requestURI.replace(contextPath, ""));
        // 获取上游网关传递的用户id
        String userId = request.getHeader(AuthConstants.USER_ID_HEADER);
        // 如果不为空，最后将用户ID存入本地线程中
        if (StrUtil.isNotBlank(userId)) {
            UserContext.setUserId(Long.valueOf(userId));
        }
        // 放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
